/*
 * Niiuzu
 * Copyright (C) 2011  Thierry Nowak
 * 
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.niiuzu.client.screen.application;

import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.GWT.UncaughtExceptionHandler;
import com.google.gwt.user.client.ui.IsWidget;
import com.mvp4g.client.annotation.Presenter;
import com.mvp4g.client.presenter.LazyPresenter;
import com.niiuzu.client.eventbus.ApplicationEventBus;

/**
 * Presenter principal de l'application en charge du routage des événements
 * principaux de l'application (notamment le passage d'un module à un second).
 */
@Presenter(view = ApplicationViewImpl.class)
public class ApplicationPresenter extends
		LazyPresenter<ApplicationView, ApplicationEventBus> {

	private UncaughtExceptionHandler uncaughtExceptionHandler;
	
	@Override
	public void bindView() {
		super.bindView();
		
		uncaughtExceptionHandler = new UncaughtExceptionHandler() {
			@Override
			public void onUncaughtException(Throwable e) {
				eventBus.errorThrown(e);
			}
		};
		GWT.setUncaughtExceptionHandler(uncaughtExceptionHandler);
	}
	
	/**
	 * Chargement du module principal suite à la connexion d'un utilisateur à
	 * l'application.
	 * 
	 * @see ApplicationEventBus#userEnteredInApplication()
	 */
	public void onUserEnteredInApplication() {
		eventBus.applicationStarted();
	}

	/**
	 * Réception de la vue du gestionnaire des données de flux RSS.
	 * 
	 * @see ApplicationEventBus#feedManagerViewLoaded(IsWidget)
	 */
	public void onFeedManagerViewLoaded(IsWidget widget) {
		view.replaceWidgetInMainPanelWith(widget);
	}

	/**
	 * Traitement appliqué lorsqu'une erreur s'est déclenchée dans
	 * l'application.
	 * 
	 * @see ApplicationEventBus#errorThrown(Throwable)
	 */
	public void onErrorThrown(Throwable caught) {
		GWT.log("Erreur", caught);
		
		view.showPopupError(caught);
	}

	/**
	 * Gestionnaire des erreurs techniques générées côté client (GWT).
	 */
	UncaughtExceptionHandler getUncaughtExceptionHandler() {
		return uncaughtExceptionHandler;
	}
}
